package com.kamfu.optionaldata.exercise06_07;


import com.kamfu.function.common.Function;
import com.kamfu.function.common.List;
import com.kamfu.optionaldata.exercise06_06.Option;

/**
 * flatMap 实现 variance 函数。一组值的方差（ variance ）表示这些值如何
 * 分布在平均值周围
 */
public class Variance {

    static Function<List<Double>, Double> sum = ds -> ds.foldLeft(0.0, a -> b -> a + b);

    static Function<List<Double>, Option<Double>> mean = ds -> ds.isEmpty() ? Option.none() : Option.some(sum.apply(ds) / ds.length());

    static Function<List<Double>, Option<Double>> variance = ds -> mean.apply(ds).flatMap(m -> mean.apply(ds.map(x -> Math.pow(x - m, 2))));
}

